using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace EventScavenger
{
    public partial class EventSourceFilter : Form
    {
        private const string AllText = "All";

        #region Constructors
        public EventSourceFilter()
        {
            InitializeComponent();
        } 
        #endregion

        #region Properties
        private List<string> selectedSources = new List<string>();
        public List<string> SelectedSources
        {
            get { return selectedSources; }
            set { selectedSources = value; }
        }
        private bool allEnabled;
        public bool AllEnabled
        {
            get { return allEnabled; }
            set { allEnabled = value; }
        }
        private bool allowNone = false;
        public bool AllowNone
        {
            get { return allowNone; }
            set { allowNone = value; }
        }
        #endregion

        #region Private stuff
        private EventScavengerDAL sqlEventSource;
        private bool selfChecking = false;
        private List<string> availableSources;
        private void ShowLoadingMessage()
        {
            lvwEventSources.Items.Clear();
            lvwEventSources.Items.Add("Loading...");
            System.Windows.Forms.Application.DoEvents();
        }
        private void LoadListView()
        {
            ListViewItem lvwi;
            if ((sqlEventSource.AvailableSources != null) && (sqlEventSource.AvailableSources.Count > 0))
            {
                availableSources = sqlEventSource.AvailableSources;
            }
            else
            {
                LoadSources();
            }
            Cursor.Current = Cursors.WaitCursor;
            selfChecking = true;
            lvwEventSources.Items.Clear();
            try
            {
                lvwEventSources.BeginUpdate();
                lvwi = new ListViewItem(AllText);
                if (allEnabled)
                {
                    lvwi.Checked = true;
                }
                lvwEventSources.Items.Add(lvwi);
                foreach (string source in availableSources)
                {
                    lvwi = new ListViewItem(source);
                    lvwi.Checked = (selectedSources.Contains(source)) || allEnabled;
                    lvwEventSources.Items.Add(lvwi);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                lvwEventSources.EndUpdate();
            }
            Cursor.Current = Cursors.Default;
            selfChecking = false;   
        }
        private void LoadSources()
        {
            availableSources = sqlEventSource.GetSourceList();
        }
        #endregion

        public DialogResult Show(EventScavengerDAL sqlEventSource) 
        {
            this.sqlEventSource = sqlEventSource;
            return ShowDialog();
        }

        #region Form events
        private void EventSourceFilter_Load(object sender, EventArgs e)
        {
            if ((Properties.Settings.Default.EventSourceFilterLocation != null) && (!Properties.Settings.Default.EventSourceFilterLocation.Equals(new Point(0, 0))))
            {
                this.Location = Properties.Settings.Default.EventSourceFilterLocation;
            }
            if ((Properties.Settings.Default.EventSourceFilterSize != null) && (!Properties.Settings.Default.EventSourceFilterSize.Equals(new Size(0, 0))))
            {
                this.Size = Properties.Settings.Default.EventSourceFilterSize;
            }
            
            //ensuring the previously selected item is visible again on startup
            new System.Threading.Thread(delegate()
                {
                    this.Invoke((MethodInvoker)delegate()
                        {
                            ShowLoadingMessage();
                            System.Threading.Thread.Sleep(500);
                            LoadListView();
                        }
                    );
                }
            ).Start();
        }

        private void EventSourceFilter_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                Properties.Settings.Default.EventSourceFilterLocation = this.Location;
                Properties.Settings.Default.EventSourceFilterSize = this.Size;
            }
            Properties.Settings.Default.Save();
        }

        private void lvwEventSources_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            int selectedCount = 0;
            if (!selfChecking)
            {
                selfChecking = true;
                if (e.Item.Text == AllText)
                {
                    foreach (ListViewItem lvwi in lvwEventSources.Items)
                    {
                        if (lvwi.Text != AllText)
                        {
                            lvwi.Checked = e.Item.Checked;
                        }
                    }
                }
                else
                {
                    if (!e.Item.Checked)
                    {
                        lvwEventSources.Items[0].Checked = false;
                    }
                    else
                    {
                        bool testAll = true;
                        foreach (ListViewItem lvwi in lvwEventSources.Items)
                        {
                            if ((lvwi.Text != AllText) && (!lvwi.Checked))
                            {
                                testAll = false;
                            }
                        }
                        lvwEventSources.Items[0].Checked = testAll;
                    }
                }
                selfChecking = false;
                foreach (ListViewItem lvwi in lvwEventSources.Items)
                {
                    if (lvwi.Checked)
                        selectedCount++;
                }
                cmdOK.Enabled = (selectedCount > 0) || allowNone;
            }

        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            selectedSources = new List<string>();
            foreach (ListViewItem lvwi in lvwEventSources.Items)
            {
                if (lvwi.Text != AllText)
                {
                    if (lvwi.Checked)
                        selectedSources.Add(lvwi.Text);
                }
                else
                    allEnabled = lvwi.Checked;
            }
            this.DialogResult = DialogResult.OK;
            Close();
        }

        private void cmdReload_Click(object sender, EventArgs e)
        {
            ShowLoadingMessage();
            LoadSources();
            LoadListView();
        }

        private void EventSourceFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                Close();
        }
        #endregion
        
        #region Quick filter
        private void txtQuickSelect_TextChanged(object sender, EventArgs e)
        {
            if (txtQuickSelect.Text.Length > 0)
            {
                timerQuickSelect.Enabled = false; //cancel any previous event
                timerQuickSelect.Enabled = true;
            }
        }
        private void timerQuickSelect_Tick(object sender, EventArgs e)
        {
            timerQuickSelect.Enabled = false;
            if (txtQuickSelect.Text.Length > 0)
            {
                string quickFilter = txtQuickSelect.Text.ToLower();
                selfChecking = true;
                foreach (ListViewItem lvi in lvwEventSources.Items)
                {
                    if (lvi.Text != AllText)
                    {
                        lvi.Checked = lvi.Text.ToLower().Contains(quickFilter);
                    }
                    else
                    {
                        lvi.Checked = false;
                    }
                }
                selfChecking = false;
                cmdOK.Enabled = (lvwEventSources.CheckedItems.Count > 0) || allowNone;
            }
        }
        #endregion
    }
}